<template>
    <div>
        <div class="mx-4 my-8 text-2xl">问题管理</div>
        <div class="m-4">
            <avue-crud
                ref="crudRef"
                :option="option"
                :data="data"
                v-model:page="page"
                @row-save="rowSave"
                @row-update="rowUpdate"
                @row-del="rowDel"
                @search-change="searchChange"
                @search-reset="resetChange"
                @refresh-change="refreshChange"
                @size-change="sizeChange"
                @current-change="currentChange"
            >
                <template #options="{ row }">
                    <div v-for="item in row.options">{{ item.id }}. {{ item.content }}</div>
                </template>
            </avue-crud>
        </div>
    </div>
</template>

<script setup lang="ts">
import { add, DBKeys, del, getList, update } from '@/apis/commonCrud'
import type { AvueCrudOption } from '@smallwei/avue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref } from 'vue'

const page = ref({
    total: 10,
    currentPage: 1,
    pageSize: 10,
})
const option = ref<AvueCrudOption>({
    index: true,
    column: [
        {
            label: '案例id',
            prop: 'teachCaseId',
            type: 'table',
            search: true,
            children: {
                column: [
                    {
                        label: 'id',
                        prop: 'id',
                    },
                    {
                        label: '标题',
                        prop: 'title',
                        search: true,
                    },
                    {
                        label: '标识',
                        prop: 'key',
                    },
                ],
            },
            onLoad: async ({ page, value, data }, callback) => {
                if (value && value !== 'add') {
                    const res = await getList('teachCases', {
                        id: value,
                    })
                    if (res.success) {
                        callback({
                            teachCase: res.data.rows[0],
                        })
                    }
                    return
                }
                if (!page) return
                const res = await getList('teachCases', {
                    ...data,
                    page: page.currentPage,
                    pageSize: 10,
                })
                if (res.success) {
                    callback({
                        total: res.data.count,
                        data: res.data.rows,
                    })
                }
            },
            props: {
                label: 'key',
                value: 'id',
            },
            formatter: (value) => {
                if (value.teachCase) {
                    return value.teachCase.key
                }
            },
            rules: [
                {
                    required: true,
                    message: '必填项',
                    trigger: 'blur',
                },
            ],
        },
        {
            label: '问题类型',
            prop: 'type',
            type: 'select',
            value: 'singleChoice',
            dicData: [{ label: '单选', value: 'singleChoice' }],
        },
        {
            label: '触发时机',
            prop: 'trigger',
            type: 'select',
            allowCreate: true,
            filterable: true,
            dicData: [
                {
                    label: 'ENTER_PAGE',
                    value: 'ENTER_PAGE',
                    desc: '进入页面后',
                },
            ],
        },
        {
            label: '知识点',
            prop: 'point',
        },
        {
            label: '问题',
            prop: 'content',
            type: 'textarea',
            search: true,
            span: 24,
        },
        {
            label: '选项列表',
            prop: 'options',
            type: 'dynamic',
            span: 24,
            children: {
                index: false,
                type: 'form',
                rowAdd: (done) => {
                    done({ id: 'A' })
                },
                column: [
                    {
                        label: '标号',
                        prop: 'id',
                        width: 50,
                    },
                    {
                        label: '选项内容',
                        prop: 'content',
                    },
                ],
            },
        },
        {
            label: '答案',
            prop: 'answer',
        },
    ],
})
const data = ref([])
const searchParams = ref({
    page: 1,
    pageSize: 10,
})

const dbName: DBKeys = 'questions'

const getData = async (sParams = searchParams.value) => {
    const res = await getList(dbName, sParams, [
        {
            model: 'teachCases',
            attributes: ['id', 'title', 'key'],
            as: 'teachCase',
        }
    ])
    if (!res.success) {
        ElMessage.error('获取数据失败')
        return
    }
    data.value = res.data.rows
    page.value.total = res.data.count
}

getData()

const rowSave = async (form, done, loading) => {
    if (form.options) {
        form.options = form.options.map((item) => {
            return {
                id: item.id,
                content: item.content,
            }
        })
    }
    const res = await add(dbName, form)
    if (!res.success) {
        ElMessage.error('添加失败')
        return
    }
    loading()
    ElMessage.success('添加成功')
    await getData()
    done()
}

const rowDel = async (row, _index, done) => {
    const confirm = await ElMessageBox.confirm('确定要删除吗？')

    if (confirm !== 'confirm') {
        done()
        return
    }

    const res = await del(dbName, row.id)
    if (!res.success) {
        ElMessage.error('删除失败')
        return
    }
    ElMessage.success('删除成功')
    await getData()
    done()
}

const rowUpdate = async (form, _index, done, loading) => {
    if (form.options) {
        form.options = form.options.map((item) => {
            return {
                id: item.id,
                content: item.content,
            }
        })
    }
    const res = await update(dbName, form.id, form)
    if (!res.success) {
        ElMessage.error('修改失败')
        return
    }
    loading()
    ElMessage.success('修改成功')
    await getData()
    done()
}

const resetChange = () => {
    const newSearchParams = {
        page: 1,
        pageSize: page.value.pageSize,
    }
    searchParams.value = newSearchParams
}

const searchChange = async (params, done) => {
    const newSearchParams = {
        page: 1,
        pageSize: page.value.pageSize,
        ...params,
    }
    searchParams.value = newSearchParams
    await getData(newSearchParams)
    done()
}
const refreshChange = () => {
    getData()
}

const sizeChange = (val) => {
    page.value.pageSize = val
    const newSearchParams = {
        page: 1,
        pageSize: val,
    }
    searchParams.value = newSearchParams
    getData(newSearchParams)
}

const currentChange = (val) => {
    page.value.currentPage = val
    const newSearchParams = {
        ...searchParams.value,
        page: val,
        pageSize: page.value.pageSize,
    }
    searchParams.value = newSearchParams
    getData(newSearchParams)
}
</script>

<style scoped></style>
